package service.impl;

import bean.Menu;
import bean.Role;
import bean.Users;
import dao.RoleDao;
import dao.UsersDao;
import dao.impl.RoleDaoImpl;
import dao.impl.UsersDaoImpl;
import service.UsersService;

import java.util.ArrayList;
import java.util.List;

public class UsersServiceImpl implements UsersService {

    private UsersDao usersDao = new UsersDaoImpl();
    private RoleDao roleDao = new RoleDaoImpl();

    @Override
    public Users login(String userName, String passWord) {

        Users users = usersDao.login(userName,passWord);

        if (users==null){
            return null;
        }

        //根据角色id查询角色，菜单信息（三表联查）
        Integer roleId = users.getRoleId();
        Role role = roleDao.findById(roleId);

        //需要对菜单进行分级
        List<Menu> menuList = role.getMenuList();
        //保存分级以后的菜单
        List<Menu> newMenuList = new ArrayList<>();
        for(Menu menu:menuList){
            if (menu.getUpMenuId()==0){
                List<Menu> secondList = new ArrayList<>();
                for(Menu second:menuList){
                    if (second.getUpMenuId()==menu.getMenuId()){
                        secondList.add(second);
                    }
                }
                menu.setSecondMenuList(secondList);
                newMenuList.add(menu);
            }
        }
        role.setMenuList(newMenuList);
        users.setRole(role);

        return users;
    }

    @Override
    public List<Users> getUsersList(int pageIndex, Integer pageSize) {
        return usersDao.getUsersList(pageIndex,pageSize);
    }

    @Override
    public int total() {
        return usersDao.total();
    }

    @Override
    public int insert(Users users) {
        return usersDao.insert(users);
    }

    @Override
    public Users findById(int userId) {
        return usersDao.findById(userId);
    }

    @Override
    public int update(Users user) {
        return usersDao.update(user);
    }

    @Override
    public int delete(int userId) {
        return usersDao.delete(userId);
    }
}
